import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _applyDecoratedDescriptor from "@babel/runtime/helpers/esm/applyDecoratedDescriptor";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _isFunction from "lodash/isFunction";

var _dec, _dec2, _dec3, _class;

import React, { PureComponent } from 'react';
import { Layout, Menu, Icon } from 'antd';
import pathToRegexp from 'path-to-regexp';
import { Link } from 'dva/router';
import { Bind } from 'lodash-decorators';
import { openTab } from "../../utils/menuTab";
import intl from "../../utils/intl";
import { urlToList } from "../_utils/pathTools";
import cpaasDefaultIcon from "../../assets/cpaas-default-favicon.png";
import styles from "./index.less?modules";
var Sider = Layout.Sider;
var SubMenu = Menu.SubMenu;

var getIcon = function getIcon(icon) {
  if (typeof icon === 'string' && icon.indexOf('http') === 0) {
    return /*#__PURE__*/React.createElement("img", {
      src: icon,
      alt: "",
      className: "".concat(styles.icon, " sider-menu-item-img")
    });
  }

  if (typeof icon === 'string') {
    return /*#__PURE__*/React.createElement(Icon, {
      type: icon
    });
  }

  return icon;
};
/**
 * Recursively flatten the data
 * [{path:string},{path:string}] => {path,path2}
 * @param  menu
 */


export var getFlatMenuKeys = function getFlatMenuKeys(menu) {
  return menu.reduce(function (keys, item) {
    keys.push(item.path);

    if (item.children) {
      return keys.concat(getFlatMenuKeys(item.children));
    }

    return keys;
  }, []);
};
/**
 * Recursively flatten the data
 * [{path:string},{path:string}] => {path,path2}
 * @param  menu
 */

export var getMenuIdToDataMap = function getMenuIdToDataMap(menu) {
  return menu.reduce(function (map, item) {
    return (// map[item.id] = item;
      // if (item.children) {
      //   return ;
      // }
      // return map;
      _objectSpread(_objectSpread({}, map), {}, _defineProperty({}, item.id, item), item.children ? getMenuIdToDataMap(item.children) : {})
    );
  }, {});
};
/**
 * Find all matched menu keys based on paths
 * @param  flatMenuKeys: [/abc, /abc/:id, /abc/:id/info]
 * @param  paths: [/abc, /abc/11, /abc/11/info]
 */

export var getMenuMatchKeys = function getMenuMatchKeys(flatMenuKeys, paths) {
  return paths.reduce(function (matchKeys, path) {
    return matchKeys.concat(flatMenuKeys.filter(function (item) {
      return pathToRegexp(item).test(path);
    }));
  }, []);
};
/**
 * Find all matched menu keys based on paths
 * @param  menuConfig: menu config
 * @param  pathname: /abc/11/info
 */

export var getMenuMatchIds = function getMenuMatchIds(menuIdToDataMap, pathname) {
  var currentMenuId = '';

  if (!currentMenuId) {
    var paths = urlToList(pathname).reverse();
    var menuConfig = Object.values(menuIdToDataMap);
    paths.some(function (path) {
      menuConfig.some(function (item) {
        if (pathToRegexp(item.path).test(path)) {
          currentMenuId = item.id;
        }

        return currentMenuId;
      });
      return currentMenuId;
    });
  }

  var currentMenuIdPath = [];

  while (menuIdToDataMap[currentMenuId]) {
    currentMenuIdPath.push("".concat(currentMenuId));
    currentMenuId = menuIdToDataMap[currentMenuId].parentId;
  }

  currentMenuIdPath = currentMenuIdPath.reverse();
  return currentMenuIdPath;
};
var SiderMenu = (_dec = Bind(), _dec2 = Bind(), _dec3 = Bind(), (_class = /*#__PURE__*/function (_PureComponent) {
  _inherits(SiderMenu, _PureComponent);

  var _super = _createSuper(SiderMenu);

  function SiderMenu(props) {
    var _this;

    _classCallCheck(this, SiderMenu);

    _this = _super.call(this, props);

    _this.getSubMenuOrItem = function (item) {
      if (item.children && item.children.some(function (child) {
        return child.name;
      })) {
        var childrenItems = _this.getNavMenuItems(item.children); // 当无子菜单时就不展示菜单


        if (childrenItems && childrenItems.length > 0) {
          return /*#__PURE__*/React.createElement(SubMenu, {
            title: item.icon ? /*#__PURE__*/React.createElement("span", null, getIcon(item.icon), /*#__PURE__*/React.createElement("span", null, item.name && intl.get(item.name).d(item.name))) : item.name,
            key: item.id
          }, childrenItems);
        }

        return null;
      }

      return /*#__PURE__*/React.createElement(Menu.Item, {
        key: item.id
      }, _this.getMenuItemPath(item));
    };

    _this.getNavMenuItems = function (menusData) {
      if (!menusData) {
        return [];
      }

      return menusData.filter(function (item) {
        return item.name && !item.hideInMenu;
      }).map(function (item) {
        // make dom
        var ItemDom = _this.getSubMenuOrItem(item);

        return _this.checkPermissionItem(item.authority, ItemDom);
      }).filter(function (item) {
        return item;
      });
    };

    _this.getSelectedMenuKeys = function () {
      var pathname = _this.props.location.pathname;
      return getMenuMatchIds(_this.menuIdToDataMap, pathname, _this.menuId);
    };

    _this.conversionPath = function (path) {
      if (path && path.indexOf('http') === 0) {
        return path;
      }

      return "/".concat(path || '').replace(/\/+/g, '/');
    };

    _this.checkPermissionItem = function (authority, ItemDom) {
      if (_this.props.Authorized && _this.props.Authorized.check) {
        var check = _this.props.Authorized.check;
        return check(authority, ItemDom);
      }

      return ItemDom;
    };

    _this.isMainMenu = function (key) {
      return key && _this.menus.some(function (item) {
        return item.id === key;
      });
    };

    _this.handleOpenChange = function (openKeys) {
      var lastOpenKey = openKeys[openKeys.length - 1];
      var moreThanOne = openKeys.filter(function (openKey) {
        return _this.isMainMenu(openKey);
      }).length > 1;

      _this.setState({
        openKeys: moreThanOne ? [lastOpenKey] : _toConsumableArray(openKeys)
      }); // this.setState({
      //   openKeys,
      // });

    };

    _this.menus = props.menuData;
    _this.menuIdToDataMap = getMenuIdToDataMap(props.menuData);
    _this.state = {
      openKeys: _this.getDefaultCollapsedSubMenus(props),
      logo: cpaasDefaultIcon,
      prevLogo: cpaasDefaultIcon
    };
    return _this;
  }

  _createClass(SiderMenu, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var logo = this.props.logo;
      var prevLogo = this.state.prevLogo;

      if (prevLogo !== logo) {
        // 有 logo 开始 懒加载 logo
        if (logo) {
          var img = new Image();
          img.onload = this.updateLogo;
          img.onerror = this.setDefaultLogo;
          img.src = logo;
        }
      }
    }
  }, {
    key: "updateLogo",
    value: function updateLogo() {
      var logo = this.props.logo;
      this.setState({
        logo: logo
      });
    }
  }, {
    key: "setDefaultLogo",
    value: function setDefaultLogo() {
      this.setState({
        logo: cpaasDefaultIcon
      });
    } //  eslint-disable-next-line

  }, {
    key: "UNSAFE_componentWillReceiveProps",
    value: function UNSAFE_componentWillReceiveProps(nextProps) {
      if (nextProps.location.pathname !== this.props.location.pathname) {
        this.setState({
          openKeys: this.getDefaultCollapsedSubMenus(nextProps)
        });
      }

      if (nextProps.menuData !== this.props.menuData) {
        this.menus = nextProps.menuData;
        this.menuIdToDataMap = getMenuIdToDataMap(nextProps.menuData);
      } // 更新 logo


      if (nextProps.logo !== this.state.prevLogo) {
        if (nextProps.logo) {
          // 有 logo 开始 懒加载 logo
          var img = new Image();
          img.onload = this.updateLogo;
          img.onerror = this.setDefaultLogo;
          img.src = nextProps.logo;
        } else {
          // 没有logo,直接设置logo,为默认logo
          this.setDefaultLogo();
        }
      }
    }
    /**
     * Convert pathname to openKeys
     * /list/search/articles = > ['list','/list/search']
     * @param  props
     */

  }, {
    key: "getDefaultCollapsedSubMenus",
    value: function getDefaultCollapsedSubMenus(props) {
      var _ref = props || this.props,
          pathname = _ref.location.pathname;

      return getMenuMatchIds(this.menuIdToDataMap, pathname, this.menuId);
    }
    /**
     * 判断是否是http链接.返回 Link 或 a
     * Judge whether it is http link.return a or Link
     * @memberof SiderMenu
     */

  }, {
    key: "getMenuItemPath",
    value: function getMenuItemPath(item) {
      var _this2 = this;

      var createHref = this.props.history.createHref;
      var itemPath = this.conversionPath(item.path);
      var icon = getIcon(item.icon);
      var target = item.target,
          name = item.name; // Is it a http link

      if (/^https?:\/\//.test(itemPath)) {
        return /*#__PURE__*/React.createElement("a", {
          href: itemPath,
          target: target
        }, icon, /*#__PURE__*/React.createElement("span", null, name && intl.get(name).d(name)));
      }

      return /*#__PURE__*/React.createElement("a", {
        // href={`#${itemPath}`}
        href: createHref({
          pathname: itemPath
        }),
        target: target,
        onClick: function onClick(e) {
          if (_isFunction(e && e.preventDefault)) {
            e.preventDefault();
          }

          _this2.menuId = item.id; // 之前的逻辑

          if (_this2.props.isMobile) {
            if (_isFunction(_this2.props.onCollapse)) {
              _this2.props.onCollapse(true);
            }
          } // 打开菜单


          openTab({
            icon: item.icon,
            title: item.name,
            key: item.path,
            closable: true,
            search: item.search
          });
        }
      }, icon, /*#__PURE__*/React.createElement("span", null, name && intl.get(name).d(name)));
    }
    /**
     * get SubMenu or Item
     */

  }, {
    key: "render",
    value: function render() {
      var _this$props = this.props,
          title = _this$props.title,
          collapsed = _this$props.collapsed,
          onCollapse = _this$props.onCollapse;
      var _this$state = this.state,
          logo = _this$state.logo,
          openKeys = _this$state.openKeys; // Don't show popup menu when it is been collapsed

      var menuProps = collapsed ? {} : {
        openKeys: openKeys,
        onOpenChange: this.handleOpenChange
      }; // if pathname can't match, use the nearest parent's key

      var selectedKeys = this.getSelectedMenuKeys();

      if (!selectedKeys.length) {
        selectedKeys = [openKeys[openKeys.length - 1]];
      }

      return /*#__PURE__*/React.createElement(Sider, {
        trigger: null,
        collapsible: true,
        collapsed: collapsed,
        breakpoint: "lg",
        onCollapse: onCollapse,
        width: 256,
        className: styles.sider
      }, /*#__PURE__*/React.createElement("div", {
        className: styles.logo,
        key: "logo"
      }, /*#__PURE__*/React.createElement(Link, {
        to: "/"
      }, /*#__PURE__*/React.createElement("img", {
        src: logo,
        alt: ""
      }), !collapsed && /*#__PURE__*/React.createElement("h1", {
        title: title
      }, title))), /*#__PURE__*/React.createElement(Menu, Object.assign({
        key: "menu",
        theme: "dark",
        mode: "inline"
      }, menuProps, {
        selectedKeys: selectedKeys,
        style: {
          padding: '16px 0',
          width: '100%',
          flex: 'auto',
          overflowY: 'auto'
        }
      }), this.getNavMenuItems(this.menus)));
    }
  }]);

  return SiderMenu;
}(PureComponent), (_applyDecoratedDescriptor(_class.prototype, "updateLogo", [_dec], Object.getOwnPropertyDescriptor(_class.prototype, "updateLogo"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "setDefaultLogo", [_dec2], Object.getOwnPropertyDescriptor(_class.prototype, "setDefaultLogo"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "getMenuItemPath", [_dec3], Object.getOwnPropertyDescriptor(_class.prototype, "getMenuItemPath"), _class.prototype)), _class));
export { SiderMenu as default };